<template>
  <scroll-view
    class="h-screen"
    scroll-y
    :refresher-triggered="refreshing"
    refresher-enabled
    @refresherrefresh="onRefresh"
    @scrolltolower="onReachBottom"
  >
    <UniAdminPanel
      ref="panelRef"
      :fetcher="fetcher"
      @add="onAdd"
      @edit="onEdit"
      @delete="onDelete"
    >
      <!-- 筛选 -->
      <template #filters>
        <view class="flex items-center gap-2">
          <wd-input
            v-model="filters.keyword"
            placeholder="请输入物品名称"
            clearable
            class="flex-1"
          />
          <wd-button type="success" size="small" @click="applyFilters"
            >搜索</wd-button
          >
          <wd-button size="small" plain @click="resetFilters">重置</wd-button>
        </view>
      </template>

      <!-- 列表项 -->
      <template #item="{ row }">
        <view
          class="p-3 rounded-xl bg-white shadow-sm flex justify-between items-center"
        >
          <view class="flex flex-col">
            <view class="font-medium text-base">{{ row.item_name }}</view>
            <view class="text-sm text-gray-500 mt-1"
              >价格：{{ row.price }} 元</view
            >
            <view v-if="row.description" class="text-sm text-gray-400 mt-1"
              >说明：{{ row.description }}</view
            >
            <view class="text-sm text-gray-400 mt-1"
              >创建时间：{{ row.createdAt }}</view
            >
          </view>
          <view class="flex gap-2 ml-3">
            <wd-button size="small" type="primary" plain @click="onEdit(row)"
              >编辑</wd-button
            >
            <wd-button size="small" type="error" plain @click="onDelete(row)"
              >删除</wd-button
            >
          </view>
        </view>
      </template>
    </UniAdminPanel>
  </scroll-view>

  <!-- 弹层 -->
  <wd-overlay v-model:show="showForm" position="center" :maskClosable="false">
    <view class="wrapper">
      <view class="w-[85%] bg-white rounded-xl flex flex-col px-4 py-6">
        <view class="text-lg font-bold mb-4 text-center">{{ formTitle }}</view>

        <wd-form ref="formRef" :model="formModel">
          <wd-cell-group border>
            <wd-input
              label="物品名称"
              label-width="90px"
              v-model="formModel.item_name"
              clearable
              placeholder="请输入物品名称"
              :rules="[{ required: true, message: '请填写物品名称' }]"
            />
            <wd-input
              label="价格"
              label-width="90px"
              type="number"
              v-model.number="formModel.price"
              clearable
              placeholder="请输入价格"
              :rules="[{ required: true, message: '请填写价格' }]"
            />
            <wd-input
              label="说明"
              label-width="90px"
              v-model="formModel.description"
              clearable
              placeholder="请输入说明（可选）"
            />
          </wd-cell-group>

          <view class="flex justify-end gap-2 mt-4">
            <wd-button size="small" plain @click="showForm = false"
              >取消</wd-button
            >
            <wd-button type="primary" size="small" @click="handleSubmit"
              >保存</wd-button
            >
          </view>
        </wd-form>
      </view>
    </view>
  </wd-overlay>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import UniAdminPanel from '@/components/Table/tableComponet.vue'
import { useToast } from 'wot-design-uni'
import {
  getrepairpriceList,
  addrepairprice,
  updaterepairprice,
  deleterepairprice
} from '@/api/price'

interface RepairPrice {
  id: number
  item_name: string
  price: number
  description?: string | null
  createdAt: Date
  updatedAt: Date
}

const { success: showSuccess } = useToast()
const panelRef = ref<any>(null)
const refreshing = ref(false)
const filters = reactive({ keyword: '' })
const showForm = ref(false)
const formTitle = ref('')

const formModel = reactive<RepairPrice>({
  id: 0,
  item_name: '',
  price: 0,
  description: '',
  createdAt: new Date(),
  updatedAt: new Date()
})

const formRef = ref<any>(null)

// fetcher 从接口获取价格列表
const fetcher = async ({ page = 1, size = 10 }: any) => {
  try {
    const res = await getrepairpriceList<any, RepairPrice>({
      page,
      pageSize: size,
      item_name: filters.keyword
    })
    const { items, total } = res.data
    return { items, hasMore: page * size < total }
  } catch (error) {
    console.error('加载价格列表失败：', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
    return { items: [], hasMore: false }
  }
}

// 下拉刷新 / 触底加载
const onRefresh = async () => {
  refreshing.value = true
  await panelRef.value?.refresh()
  refreshing.value = false
}
const onReachBottom = () => panelRef.value?.loadMore()

// 搜索 / 重置
const applyFilters = () => panelRef.value?.refresh()
const resetFilters = () => {
  filters.keyword = ''
  panelRef.value?.refresh()
}

// 新增
const onAdd = () => {
  formTitle.value = '新增价格'
  Object.assign(formModel, {
    id: 0,
    item_name: '',
    price: 0,
    description: ''
  })
  showForm.value = true
}

// 编辑
const onEdit = (row: RepairPrice) => {
  formTitle.value = '编辑价格'
  Object.assign(formModel, { ...row })
  showForm.value = true
}

// 删除
const onDelete = (row: RepairPrice) => {
  uni.showModal({
    title: '删除价格',
    content: `确定删除 "${row.item_name}" 吗？`,
    success: async (res: any) => {
      if (res.confirm) {
        try {
          await deleterepairprice({ id: row.id })
          showSuccess({ msg: '删除成功' })
          panelRef.value?.refresh()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }
    }
  })
}

// 保存（新增或编辑）
const handleSubmit = async () => {
  const isEdit = formModel.id !== 0
  try {
    if (isEdit) {
      await updaterepairprice({ ...formModel })
      showSuccess({ msg: '修改成功' })
    } else {
      await addrepairprice({ ...formModel })
      showSuccess({ msg: '新增成功' })
    }
    showForm.value = false
    panelRef.value?.refresh()
  } catch (error) {
    console.error('保存失败：', error)
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
